﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Specialized;
using System.Collections.Generic;
using wm.Alipay;
using msBsc.AppLogic.DataAlc;

/// <summary>
/// 功能：服务器异步通知页面
/// 版本：3.3
/// 日期：2012-07-10
/// 说明：
/// 以下代码只是为了方便商户测试而提供的样例代码，商户可以根据自己网站的需要，按照技术文档编写,并非一定要使用该代码。
/// 该代码仅供学习和研究支付宝接口使用，只是提供一个参考。
/// 
/// ///////////////////页面功能说明///////////////////
/// 创建该页面文件时，请留心该页面文件中无任何HTML代码及空格。
/// 该页面不能在本机电脑测试，请到服务器上做测试。请确保外部可以访问该页面。
/// 该页面调试工具请使用写文本函数logResult。
/// 如果没有收到该页面返回的 success 信息，支付宝会在24小时内按一定的时间策略重发通知
/// </summary>
public partial class wmnotify_url : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        string requUrl = Request.Url.ToString();
        string trade_no = Request.Params["trade_no"];         //支付宝交易号
        string order_no = Request.Params["out_trade_no"];     //获取订单号
        string total_fee = Request.Params["price"];           //获取总金额
        string subject = Request.Params["subject"];           //商品名称、订单名称
        string body = Request.Params["body"];                 //商品描述、订单备注、描述
        string buyer_email = Request.Params["buyer_email"];   //买家支付宝账号
        string trade_status = Request.Params["trade_status"]; //交易状态
        string refund_status = Request.Params["refund_status"];//退款状态

        trade_no = string.IsNullOrEmpty(trade_no) ? "" : trade_no;
        order_no = string.IsNullOrEmpty(order_no) ? "" : order_no;
        total_fee = string.IsNullOrEmpty(total_fee) ? "0.00" : total_fee;
        subject = string.IsNullOrEmpty(subject) ? "" : subject;
        body = string.IsNullOrEmpty(body) ? "" : body;
        buyer_email = string.IsNullOrEmpty(buyer_email) ? "" : buyer_email;
        trade_status = string.IsNullOrEmpty(trade_status) ? "" : trade_status;
        refund_status = string.IsNullOrEmpty(refund_status) ? "" : refund_status;


        using (CBizShpChargeAlipayLog objalpay = new CBizShpChargeAlipayLog())
        {
            System.Data.DataSet dsAlilog;
            //if (!blPayed)
            //{
            //    dsAlilog = objalpay.SelectByAlipayNo(trade_no);
            //}
            //else
            //{
            dsAlilog = new msBsc.Xsd.DataTds.CDmShpChargeAlipayLog();
            //}

            System.Data.DataRow drnew = dsAlilog.Tables[0].NewRow();
            drnew["ALIPAY_LOG_ID"] = objalpay.DataObj.NewID();
            drnew["CHARGE_TRADING_ID"] = "";
            drnew["ALIPAY_TRADING_NO"] = trade_no;
            drnew["OUT_TRADING_NO"] = order_no;
            drnew["TRADING_AMT"] = total_fee;
            drnew["TRADING_NME"] = subject;
            drnew["TRADING_DESC"] = requUrl;
            drnew["BUYER_EMAIL"] = buyer_email;
            drnew["TRADING_STATUS"] = trade_status;
            drnew["REFUND_STATUS"] = refund_status;
            dsAlilog.Tables[0].Rows.Add(drnew);
            objalpay.Update(dsAlilog);
        }



        SortedDictionary<string, string> sPara = GetRequestPost();

        if (sPara.Count > 0)//判断是否有带返回参数
        {
            Notify aliNotify = new Notify();
            bool verifyResult = aliNotify.Verify(sPara, Request.Form["notify_id"], Request.Form["sign"]);

            if (verifyResult)//验证成功
            {
                /////////////////////////////////////////////////////////////////////////////////////////////////////////////
                //请在这里加上商户的业务逻辑程序代码


                //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
                //获取支付宝的通知返回参数，可参考技术文档中服务器异步通知参数列表

                ////商户订单号

                //string out_trade_no = Request.Form["out_trade_no"];

                ////支付宝交易号

                //string trade_no = Request.Form["trade_no"];

                ////交易状态
                //string trade_status = Request.Form["trade_status"];

                if (Request.Form["trade_status"] == "TRADE_FINISHED" || Request.Form["trade_status"] == "TRADE_SUCCESS")
                {
                    System.Transactions.TransactionOptions transactionOption = new System.Transactions.TransactionOptions();
                    transactionOption.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
                    transactionOption.Timeout = new TimeSpan(0, 10, 0);
                    using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, transactionOption))
                    {
                        using (msBsc.AppLogic.DataAlc.CBizDjkChargeTradingLog objtradlog = new msBsc.AppLogic.DataAlc.CBizDjkChargeTradingLog())
                        {
                            objtradlog.doSaveAlipay(trade_no, order_no, total_fee, subject, body, buyer_email, trade_status, refund_status);
                        }
                        ts.Complete();
                    }
                }
                else
                {
                }

                //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——

                Response.Write("success");  //请不要修改或删除

                /////////////////////////////////////////////////////////////////////////////////////////////////////////////
            }
            else//验证失败
            {
                Response.Write("fail");
            }
        }
        else
        {
            Response.Write("无通知参数");
        }
    }

    /// <summary>
    /// 获取支付宝POST过来通知消息，并以“参数名=参数值”的形式组成数组
    /// </summary>
    /// <returns>request回来的信息组成的数组</returns>
    public SortedDictionary<string, string> GetRequestPost()
    {
        int i = 0;
        SortedDictionary<string, string> sArray = new SortedDictionary<string, string>();
        NameValueCollection coll;
        //Load Form variables into NameValueCollection variable.
        coll = Request.Form;

        // Get names of all forms into a string array.
        String[] requestItem = coll.AllKeys;

        for (i = 0; i < requestItem.Length; i++)
        {
            sArray.Add(requestItem[i], Request.Form[requestItem[i]]);
        }

        return sArray;
    }
}
